/* eslint-disable prettier/prettier */
import React, { useState, useEffect, useRef } from 'react';
import { View, Text } from 'react-native';
import styles from './styles';

const TyperWriter = ({ text, isPlaying }) => {
  const [currentText, setCurrentText] = useState('');
  const indexRef = useRef(0);
  const textRef = useRef(text);
  const timerRef = useRef(null);

  useEffect(() => {
    textRef.current = text;

    return () => {
      if (timerRef.current) {
        clearInterval(timerRef.current);
      }
    };
  }, [text]);

  useEffect(() => {
    if (isPlaying && textRef.current) {
      indexRef.current = 0;
      setCurrentText('');

      timerRef.current = setInterval(() => {
        if (indexRef.current < textRef.current.length) {
          setCurrentText(textRef.current.substring(0, indexRef.current + 1));
          indexRef.current++;
        } else {
          clearInterval(timerRef.current);
        }
      }, 100); // 你可以根据需要调整打字速度
    }
    // 如果isPlaying为false，停止动画
    else if (!isPlaying && timerRef.current) {
      clearInterval(timerRef.current);
    }
  }, [text, isPlaying]);

  return (
    <View>
      <Text style={styles.TyperWriter}>
        {isPlaying ? currentText : text}
      </Text>
    </View>
  );
};

export default TyperWriter;